package com.spider.solitaire.ace.sdk.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.spider.solitaire.ace.sdk.SpiderSABusiness;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public class SpiderSACocosBridge implements SpiderSACocosIAP {

    private static SpiderSACocosBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private Method evalString;
    private Method runOnGLThread;
    private static Handler handler = new Handler(Looper.getMainLooper());

    public static SpiderSACocosBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new SpiderSACocosBridge();
        }
        return callbackApi;
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    @Override
    public void XSSdkCallback(String action, String jsonData) {
        if (mainGameActivity != null && mainGameActivity.get() != null) {

            if (runOnGLThread==null){
                initRunOnGLThread();
            }
            if (evalString == null){
                initEvalString();
            }

           callBack(action,jsonData);
        }
    }

    private void callBack(String action, String jsonData) {
        handler.post(() -> {
            try {
                runOnGLThread.invoke(mainGameActivity.get(), new Runnable() {
                    @Override
                    public void run() {
                        try {
                            evalString.invoke(null, String.format("window.SpiderCallback('%s','%s')", action, jsonData));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    private void initEvalString() {
        try {
            Class clzBridge = Class.forName("org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge", false, SpiderSABusiness.context.getClassLoader());
            evalString = clzBridge.getDeclaredMethod("evalString", String.class);
            evalString.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initRunOnGLThread() {
        try {
            Class clzCocos2dAct = Class.forName("org.cocos2dx.lib.Cocos2dxActivity", false, SpiderSABusiness.context.getClassLoader());
            runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
            runOnGLThread.setAccessible(true);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
